﻿using System;
using System.Collections.Generic;
using System.Text;
using ProtocolVN.Framework.Win;
using System.Data;
using DevExpress.XtraGrid.Views.Grid;
using ProtocolVN.Framework.Core;
using System.Drawing;

namespace ProtocolVN.Framework.Win
{
    public interface ISoTien
    {
        decimal GetSoTienThu();
    }

    public class RBTienThanhToanExt:RangBuocRule
    {
        DataTable ConLai;
        PhieuType Src;
        long SrcID;
        PhieuType Des;
        long DesID;
        object DesObj;
        PLGridView DesGrid;
        #region RangBuocRule Members

        List<InvalidInfo> RangBuocRule.Check()
        {
            List<InvalidInfo> ret = new List<InvalidInfo>();
            List<object[]> LObj = DAPhieuLienQuan.GetListPhieuLienQuan(SrcID, Src, Des);
            bool flag = Check(Src, SrcID, LObj, Des, DesID, DesObj, DesGrid);
            if (flag == false)
            {
                ret.Add(new InvalidInfo(
                    "Vi phạm ràng buộc về tổng tiền thanh toán",
                    "Vui lòng kiểm tra lại các thông tin liên quan số tiền phải thu, số tiền đã thu ở các phiếu",
                    InvalidInfo.InvalidType.ERROR));
            }
            return ret;
        }

        #endregion
        public  RBTienThanhToanExt() { }
        public RBTienThanhToanExt(PhieuType Src, long SrcID, PhieuType Des, long DesID,
            object DesObj, PLGridView DesGrid)
        {
            this.Src = Src;
            this.SrcID = SrcID;
            this.Des = Des;
            this.DesID = DesID;
            this.DesObj = DesObj;
            this.DesGrid = DesGrid;
        }
        private bool Check(PhieuType Src, long SrcID, List<object[]> LObj, PhieuType Des,
           long DesID, object DesObj, PLGridView DesGrid)
        {
            ISoTien data = (ISoTien)DesObj;
            DataTable dt_lienquan = RangBuocThanhTienHelp.CreateSoTien(LObj,SrcID, DesID);
            DataTable dt_sum = RangBuocThanhTienHelp.CreateSoTien(Src, SrcID);

            if (data != null)
            {
                if (dt_lienquan.Rows.Count == 0)
                {
                    dt_lienquan.Rows.Add(dt_lienquan.NewRow());
                    dt_lienquan.Rows[0]["SO_TIEN"] = 0;
                }
                dt_lienquan.Rows[0]["SO_TIEN"] = data.GetSoTienThu()+
                    HelpNumber.ParseDecimal(dt_lienquan.Rows[0]["SO_TIEN"]);                                               
            }
            bool chapnhan = RangBuocThanhTienHelp.KiemTraRangBuoc(dt_sum, dt_lienquan);
            ConLai=dt_sum.Clone();
            if(data!=null)
            {
                if (!chapnhan)
                {  decimal tong_tien=HelpNumber.ParseDecimal(dt_sum.Rows[0][0]);
                   decimal so_tien_lienquan=HelpNumber.ParseDecimal(dt_lienquan.Rows[0][0]);
                   string vi_pham="Vi phạm ràng buộc về Số tiền. Số tiền cho phép: <=" +
                                    (tong_tien - (so_tien_lienquan-data.GetSoTienThu())) + " !";
                   RangBuocThanhTienHelp.ShowErrorOnGrid( DesGrid,vi_pham);
                   return false;
                }
            }
            else
            {
                 if (chapnhan)
                 {
                    if (dt_lienquan == null || dt_lienquan.Rows.Count == 0)
                        ConLai = dt_sum;
                    else
                    {
                        dt_sum.Rows[0]["SO_TIEN"] = HelpNumber.ParseDecimal(dt_sum.Rows[0]["SO_TIEN"]) -
                                                  HelpNumber.ParseDecimal(dt_lienquan.Rows[0]["SO_TIEN"]);
                        ConLai = dt_sum;
                    }
                    if (HelpNumber.ParseDecimal(ConLai.Rows[0][0]) == 0)
                        return false;
                 } 
                 else return false;
            }
            return true;
        }
        public static bool Check(RBTienThanhToanExt rule, PhieuType Src, long SrcID,
           PhieuType Des, long DesID, Object DesObj, PLGridView DesGrid)
        {
            //Lay danh sach cac phieu thuoc nhom phieu des duoc tao tu (Src, SrcID)
            //Duoc xay dung tu PhieuLienQuan List (TYPE_ID, ID)            
            List<object[]> LObj = DAPhieuLienQuan.GetListPhieuLienQuan(SrcID, Src, Des);
            return rule.Check(Src, SrcID, LObj, Des, DesID, DesObj, DesGrid);
        }
        public DataTable GetConLai()
        {
            if (HelpNumber.ParseDecimal(ConLai.Rows[0]["SO_TIEN"]) <= 0)
                ConLai.Rows.RemoveAt(0);
            return ConLai;
        }
        public DataSet ListDesMoney(PhieuType Src, long id)
        {
//            string str = @"select thu.pt_id id_phieu,
//                                 (select id from dm_phieu where table_name='PHIEU_THU') loai_phieu,
//                                  thu.so_tien  from phieu_thu_ct thu
//                           where thu.object_id=1003294
//                           union
//                           select kh.pkht_id,
//                                 (select id from dm_phieu where table_name='PHIEU_KE_HOACH_THU') loai_phieu,
//                                  kh.tien_phai_thu so_tien from phieu_ke_hoach_thu_ct kh
//                           where kh.pbh_id=1003294;";
            return new DataSet();
        }
    }
    public class RangBuocThanhTienHelp
    {
        /// <summary>
        /// Tạo DataTable(HH_ID, SO_LUONG, TRONG_LUONG) lưu trữ hàng hóa, kèm số lượng, trọng lượng
        /// Thuộc 1 phiếu bất kì có loại phiếu và ID
        /// </summary>
        /// <param name="type">Loại phiếu</param>
        /// <param name="id">ID</param>
        /// <returns></returns>
        public static DataTable CreateSoTien(PhieuType type, long id)
        {
            try
            {
                string sql = "select Tong_tien  as \"SO_TIEN\" from "
                    + type.GetTableName() + " where 1=1";                             
                QueryBuilder filter = new QueryBuilder(sql);
                filter.addID(type.GetIDField(), id);
                DataSet ds = DABase.getDatabase().LoadDataSet(filter);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                PLException.AddException(ex);
                return null;
            }
        }        
        /// <summary>
        /// Tạo DataTable(SO_TIEN) lưu trữ số tiền,      
        /// </summary>
        /// <param name="LObj">Danh sách phiếu liên quan (Loại phiếu, ID)</param>
        /// <param name="Des">Loại phiếu đích</param>
        /// <param name="DesID">ID phiếu đích</param>        
        /// <returns>DataTable(SO_TIEN)</returns>
        public static DataTable CreateSoTien(List<object[]> LObj,long SrcID, long DesID)
        {
            DataTable dt_rough = new DataTable();
            DataColumn[] dc_arr = new DataColumn[] { new DataColumn("SO_TIEN")   };
            dt_rough.Columns.AddRange(dc_arr);
            dt_rough.Columns["SO_TIEN"].DataType = Type.GetType("System.Decimal");
            try
            {
                foreach (object[] obj_arr in LObj)
                {
                    PhieuType PLQ_type = (PhieuType)obj_arr[0];
                    long PLQ_id = (long)obj_arr[1];
                    if (DesID == -1 || (DesID != -1 && DesID != PLQ_id))
                    {
                        QueryBuilder filter = new QueryBuilder("select  " + PLQ_type.GetSOLGField() +
                            " as \"SO_TIEN\" from " + PLQ_type.GetTableName()
                            + "_CT" + " where 1=1");
                        filter.addID(PLQ_type.GetIDField(), PLQ_id);
                        //filter.addID("", SrcID);
                        DataSet ds = DABase.getDatabase().LoadDataSet(filter);
                        DataRow[] dr_arr = ds.Tables[0].Select();
                        foreach (DataRow dr in dr_arr)
                            dt_rough.ImportRow(dr);
                    }
                }

                DataTable dt_last = dt_rough.Clone();
                if (dt_rough.Rows.Count > 0)
                {
                    decimal tong_so_tien = HelpNumber.ParseDecimal(dt_rough.Compute("Sum(SO_TIEN)", ""));
                    DataRow row = dt_last.NewRow();
                    row["SO_TIEN"] = tong_so_tien;
                    dt_last.Rows.Add(row);
                }
                return dt_last;                
            }
            catch (Exception ex)
            {
                PLException.AddException(ex);
                return null;
            }
        } 
        /// <summary>
        /// Kiểm tra ràng buộc về so tien
        /// </summary>
        /// <param name="dt_nguon">DataTable nguồn</param>
        /// <param name="dt_dich">DataTable đích</param>
        /// <returns>DataTable miêu tả các dòng không hợp lệ</returns>
        public static bool KiemTraRangBuoc(DataTable dt_nguon, DataTable dt_dich)
        {
            if (dt_dich == null || dt_dich.Rows.Count == 0)
                return true;
            decimal tong_tien = HelpNumber.ParseDecimal(dt_nguon.Rows[0]["SO_TIEN"]);
            decimal so_tien = HelpNumber.ParseDecimal(dt_dich.Rows[0]["SO_TIEN"]);
            if (so_tien > tong_tien)
                return false;
            else return true;

        }
        public static void ShowErrorOnGrid(PLGridView gridDich, string Vi_Pham)
        {
            RangBuocSoLgTrLgHelp.AddFormatCond(gridDich);           
                gridDich.SetRowCellValue(0, gridDich.Columns["CHECK"], 1);
                gridDich.SetRowCellValue(0, gridDich.Columns["VI_PHAM"], "");                
                DataRow rowDich = gridDich.GetDataRow(0);               
                gridDich.SetRowCellValue(0, gridDich.Columns["CHECK"], 0);
                gridDich.SetRowCellValue(0, gridDich.Columns["VI_PHAM"], Vi_Pham);
                gridDich.UpdateCurrentRow();
                gridDich.OptionsView.ShowPreview = true;
                gridDich.OptionsView.AutoCalcPreviewLineCount = true;
                gridDich.PreviewFieldName = "VI_PHAM";
                gridDich.CustomDrawRowPreview +=
                    new DevExpress.XtraGrid.Views.Base.RowObjectCustomDrawEventHandler(
                        gridDich_CustomDrawRowPreview);
                
        }
        public static void gridDich_CustomDrawRowPreview(object sender, DevExpress.XtraGrid.Views.Base.RowObjectCustomDrawEventArgs e)
        {
            e.Appearance.ForeColor = Color.Red;
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            e.Appearance.Font = new Font("Tahoma", 8.25F, FontStyle.Italic);
        }         
            
        
    }
}
